<?php
declare (strict_types=1);
/**
 * 用户手机号码管理
 * @since   2021-7-13
 * @author  wwbo
 */

namespace app\controller\admin;


use app\util\ReturnCode;
use app\util\RouterTool;
use app\util\Tools;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Filesystem;
use think\Model;
use think\Response;
use app\model\UserPhone;
use think\facade\Db;
class UserPhoneManager extends Base {

    /**
     * 获取所有号码
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author wwbo
     */
    public function index(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $page = $this->request->get('page', 1);
        $status = $this->request->get('status/d');
        $uid = $this->request->get('uid/d');
        //删选条件
        if (isset($status)){
            $where = ' where up.status = '.$status;
            if(isset($uid)){
                $where = $where." and up.uid =  ".$uid;
            }
        }elseif (isset($uid)){
            $where = ' where up.uid = '.$uid;
        }else{
            $where = ' ';
        }

        $total_sql = "select count(*) as total from user_phone as up  ".$where;
        $totalNum = Db::query($total_sql);

//        dd(DB::getLastSql());
//        $totalNum = (new UserPhone())->where('status','<>',1)->count();
        $start = $limit * ($page - 1);
        $sql = "SELECT up.* ,au.username,au.nickname FROM user_phone as up LEFT JOIN admin_user as au " .
            " ON up.`uid` = au.`id` ".$where."  LIMIT {$start}, {$limit} ";
        $userInfo = Db::query($sql);
        return $this->buildSuccess(['user_phone'=>$userInfo,'total_num'=>$totalNum[0]['total']], '成功');


    }


    /**
     * 添加号码
     * @return Response
     * @author wwbo
     */
    public function add(): Response{
        $postData = $this->request->post();
        $postData['add_time'] = date('Y-m-d h:i:s', time());
        if (isset($postData['phone_num'])){
            $phone_exits = (new UserPhone())->where('phone_num',$postData['phone_num'])->find();
            if (!empty($phone_exits)){
                return $this->buildFailed(ReturnCode::PARAM_INVALID,'该号码已经存在');
            }
            $res = UserPhone::create($postData);
            if ($res === false) {
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
            }
            return $this->buildSuccess([],'操作成功');
        }
        return $this->buildFailed(ReturnCode::PARAM_INVALID,'电话号码不能为空');
    }

    /**
     * 编辑修改号码
     * @return Response
     * @author wwbo
     */
    public function edit(): Response{
        $postData = $this->request->post();
        $postData['update_time'] = date('Y-m-d h:i:s', time());
        $res = UserPhone::update($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        return $this->buildSuccess([],'操作成功');

    }

    /**
     * 删除号码
     * @return Response
     * @author wwbo
     */
    public function del(): Response{
        $id = $this->request->get('id/d');
        $res = (new UserPhone())->where('id',$id)->update(['status'=>1]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        return $this->buildSuccess([],'操作成功');
    }

    /**
     * 上传文件
     * @return Response
     * @author wwbo
     */
    public function upload(): Response {
        $path = '/upload/' . date('Ymd', time()) . '/';
        $name = $_FILES['file']['name'];
        $tmp_name = $_FILES['file']['tmp_name'];
        $error = $_FILES['file']['error'];

        if ($error) {
            switch ($error) {
                case 1:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3:
                    $error_message = '文件只被部分上传';
                    break;
                case 4:
                    $error_message = '文件不能为空';
                    break;
                default:
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            return $this->buildSuccess([
                'fileName' => $new_name,
                'fileUrl'  => $this->request->domain() . $path . $new_name
            ]);
        } else {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '文件上传失败');
        }
    }

}
